<?php
	// SQLitePDO
	// Database class PDO-SQLite
	//
	// Author: Arttu Valo
	// Date: 5.10.2006
	//
	error_reporting(E_ALL);
	
	// Include DataSource interface	
	require_once("DataSource.php");
	
	class SQLitePDO extends DataSource
	{
		// Connection variable
		private $db_connection;
		
		public function SQLitePDO($serverName, $userName, $passWord, $dbName="")
		{
			if($this->db_connection)
			{
				$this->Close();
			}
			
			$this->Connect($serverName, $userName, $passWord, $dbName);
		}
		
		// Connect
		// For SQLite, this does the same as SelectDB		
		public function Connect($serverName, $userName, $passWord, $dbName="")
		{
			if(!is_null($this->db_connection))
			{
				$this->Close();
			}
			try {
				$this->db_connection = new PDO("sqlite:$dbName");
			}
			catch(PDOException $e) {
				echo "Connection failed: " . $e->getMessage();
			}
		}
		
		// Close
		// Closes the database connection		
		public function Close()
		{
			$this->db_connection = null;
		}
		
		// SelectDB
		// Selects the database that is used		
		public function SelectDB($dbName)
		{
			$retVal = FALSE;
			try {
				$this->db_connection = new PDO("sqlite:$dbName");
				$retVal = TRUE;
			}
			catch(PDOException $e) {
				echo "Connection failed: " . $e->getMessage();
			}
			return $retVal;
		}
		
		// Query
		// Does a database query. Return values depends in query
		public function Query($sql)
		{
			$query_result = $this->db_connection->query($sql);
			
			if(empty($query_result))
			{
				return array();
			}
			
			if(strpos($sql, 'insert') === false)
			{
				$result = array();
				while($row = $query_result->fetch(PDO::FETCH_OBJ))
				{
					$result[] = $row;
				}
				
				$query_result = null;
				
				return $result;
			}
			else
			{
				$query_result = null;
				
				return $this->db_connection->lastInsertId();
			}
		}
	}

?>